<?php
/*
Plugin Name: BuddyPress Polling Plugin
Plugin URI: http://pollingplugin.com/
Description: Improves functionality for buddypress users giving a buddypress powered poll system as an option. Helps your polls go viral across your BuddyPress network. Uses the Easy Polling Plugin at its core.
Version: 1.0
Author: MYO
Author URI: http://www.make-your-offer.com
*/


add_action('init', 'bp_polling__init');

//intial options

#} URL
  global $bp_urls;

    $bp_urls['updateCheck']	 = 'http://www.epicplugins.com/api/';
	$bp_urls['regCheck']		 = 'http://www.epicplugins.com/registration/';


#} Initialisation - enqueueing scripts/styles
function bp_polling__init(){
	
wp_enqueue_script("jquery");
wp_enqueue_script('myo-bp-polling-ajax',plugins_url('/js/myo-bp-polling.js',__FILE__),array('jquery'));

 if (!is_admin()) {
wp_enqueue_style('bpcss', plugins_url('/css/bpcss.css',__FILE__) );

 }
 
 
		add_option('bp2','no','','yes'); 
		add_option('bpfbook','yes','','yes'); 
		add_option('bpjustone','yes','','yes'); 

		

 
 

}


#} for activation hook
    #} Install/uninstall
    register_activation_hook(__FILE__,'buddypoll__install');
	
	function buddypoll__install(){

		    $current_user = wp_get_current_user();    //email the current user rather than admin info more likely to reach a human email 
			$userEmail = $current_user->user_email;
		    $userName =  $current_user->user_firstname;
			$LastName =  $current_user->user_lastname;
			$plugin = 'BuddyPoll';
			
			if(get_option('bp2') == 'no'){    //only send them an install email once
			bpolls_sendReg($userEmail,$userName,$plugin);
			update_option('bp2', 'yes');
			}  
	
	}



	#} Page slugs
    global $myo_polling_slugs;
    $myo_polling_slugs['config']           = "myo_polling-plugin-config";
    $myo_polling_slugs['settings']         = "myo_polling-plugin-settings";
	$myo_polling_slugs['bpress']            = "myo_polling-plugin-bpress";



#} Add le additional admin menu hooked into Easy Polling Plugin

add_action('myo_fb_hook', 'myo_bp_polling__admin_hook');
function myo_bp_polling__admin_hook() {
	global $myo_polling_slugs;
	add_submenu_page( $myo_polling_slugs['config'], 'BuddyPress', 'BuddyPress', 'manage_options', $myo_polling_slugs['bpress'] , 'myo_polling_bp_settings' );
}
	
	add_option('bpjustone','yes','','yes');

add_action('myo_bp_style', 'myo_bp_style_hook');
function myo_bp_style_hook(){?>
	<option value="buddypress">BuddyPress</option>
<?php	
}

add_action('myo_bp_style2', 'myo_bp_style_hook2');
function myo_bp_style_hook2(){?>
	<option value="buddypress" selected>BuddyPress</option>
<?php	
}


add_action( 'wp_ajax_nopriv_myo_bp_polling_vote', 'myo_bp_polling_vote' );
add_action( 'wp_ajax_myo_bp_polling_vote', 'myo_bp_polling_vote' );

#}Settings
function myo_polling_bp_settings() {
    
    global $wpdb;    #} Req
    
    if (!current_user_can('manage_options'))  {
        wp_die( __('You do not have sufficient permissions to access this page.') );
    }
    
    
?><div id="sgpBod">
          <div class='myslogo'><?php echo '<img src="' .plugins_url( 'i/logo.png' , __FILE__ ). '" > ';   ?></div>
        <div class='mysearch'>
        	
        <?php myo_polling_header(); ?>
            
                
         <?php
         	if(isset($_GET['save'])){ 
             if ($_GET['save'] == "1"){
                myo_polling_bp_save_settings();
             }
		    }
            if(!isset($_GET['save'])){
                myo_polling_bp_html_settings();
            }
    ?></div>
</div>
<?php
}


function myo_polling_bp_html_settings(){
        
    global $wpdb, $myo_polling_slugs, $myo_polling_urls;
    
    $myoConfig = array();
    $myoConfig['bpjustone'] 		   =       get_option('bpjustone');    
    $myoConfig['bpfbook'] 		       =       get_option('bpfbook');  
    
    ?>
    

     <form action="?page=<?php echo $myo_polling_slugs['bpress']; ?>&save=1" method="post">
     <div class="postbox">
     <h3><label>General settings</label></h3>
     
     <table class="form-table" width="100%" border="0" cellspacing="0" cellpadding="6">
         
        <tr valign="top">
                        <td width="25%" align="left"><strong>Allow only one vote:</strong></td>
                        <?php if($myoConfig['bpjustone'] == 'yes'){ ?>
                        <td align="left">
                            <input type="radio" name="bpjustone" value="yes" checked> Yes
                            <input type="radio" name="bpjustone" value="no"> No
                            <br><i>Restrict votes to only one per buddypress member?</i>
                        </td>
                        <?php }else{ ?>
                         <td align="left">
                            <input type="radio" name="bpjustone" value="yes"> Yes
                            <input type="radio" name="bpjustone" value="no" checked> No
                            <br><i>Restrict votes to only one per buddypress member?</i>
                        </td>
                        <?php } ?>
         </tr>

        <tr valign="top">
                        <td width="25%" align="left"><strong>Show Facebook Comments:</strong></td>
                        <?php if($myoConfig['bpfbook'] == 'yes'){ ?>
                        <td align="left">
                            <input type="radio" name="bpfbook" value="yes" checked> Yes
                            <input type="radio" name="bpfbook" value="no"> No
                            <br><i>Show Facebook Comment Plugin under the Polls?</i>
                        </td>
                        <?php }else{ ?>
                         <td align="left">
                            <input type="radio" name="bpfbook" value="yes"> Yes
                            <input type="radio" name="bpfbook" value="no" checked> No
                            <br><i>Show Facebook Comment Plugin under the Polls?</i>
                        </td>
                        <?php } ?>
         </tr>
    </table>
    <p id="footerSub"><input class = "button-primary" type="submit" value="Save settings" /></p>
    <div class = 'inside'>
    <p>
    Depending on your site, you may wish to allow users to vote on a poll more than once. The recommended setting is only one vote per poll. This means results
    would not be skewed by someone voting multiple times on an option. However there may be circumstances where you wish to allow users more than one vote. 
    <br/></br>
    <b>Shortcode to use for a BuddyPress poll</b></br> 
    <i>[myo_bp_poll poll = ID]</i> where ID is the ID of the Easy Poll. 
    </p>
    </div>
    
    </form>
    
    
</div>

<?php }



#} Save options changes
function myo_polling_bp_save_settings(){
    
    global $wpdb;  #} Req
    
    $myoConfig = array();
    $myoConfig['bpjustone'] 				=           $_POST['bpjustone'];
	$myoConfig['bpfbook'] 					=           $_POST['bpfbook'];

    
    #} Save down
    update_option("bpjustone", $myoConfig['bpjustone']);
    update_option("bpfbook", $myoConfig['bpfbook']);


    #} Msg
    myo_polling_html_msg(0,"Saved options");
    
    #} Run standard
    myo_polling_bp_html_settings();
    
}





function myo_bp_polling_vote(){
	global $wpdb;
	$wpdb->myo_ip   = $wpdb->prefix . 'myo_ip';
	
    $repo = 0;
	$poll = (int)$_POST['poll'];
    $option = (int)$_POST['option'];
	$fid = (int)$_POST['fbook'];
	$parent = (int)$_POST['parent'];
	$fname = $_POST['fnamey'];
	
	if($fid == 0){
		exit;
	}

	$postid = $_POST['poll'];	
	$query = "SELECT myo_polling_option FROM $wpdb->myo_ip WHERE myo_polling_ip = $fid AND myo_polling_id = $postid";
	$al = $wpdb->get_var($query);
    
	if(get_option('bpjustone') == 'yes'){
	
		if($al == NULL){
			$fb = 5;
			$query = "INSERT INTO $wpdb->myo_ip ( myo_polling_id , myo_polling_ip, myo_polling_option, myo_fb, myo_fb_name) VALUES ( $postid, $fid, $option, $fb, '$fname')";
			$wpdb->query($query);
		}else{
			$oldopt = $al;
			$query = "UPDATE $wpdb->myo_ip SET myo_polling_option = $option WHERE myo_polling_ip = $fid AND myo_polling_id = $postid";
			$wpdb->query($query);
			$repo = 1;
		}
	
	}else{
		$fb = 5;
		$query = "INSERT INTO $wpdb->myo_ip ( myo_polling_id , myo_polling_ip, myo_polling_option, myo_fb, myo_fb_name) VALUES ( $postid, $fid, $option, $fb, '$fname')";
		$wpdb->query($query);
	}
	
    $votes = get_post_meta($poll,'myo-votes',true);
	$options = get_post_meta($poll,'myo-options',true);
	
    $votes_array = explode(",",$votes);
	$option_array = explode(",",$options);
   
    $votes_array[$option] = $votes_array[$option]+1;
	
	if(get_option('bpjustone') == 'yes'){
		if($oldopt != 'none'){
			if($oldopt > count($option_array)){}
			else{
			$votes_array[$oldopt] = $votes_array[$oldopt]-1;
			}
		}
	}else{}
	
	$total_votes = $wpdb->get_var( "SELECT COUNT(id) FROM $wpdb->myo_ip WHERE myo_polling_id = $postid" );
	
	$total_options = count($option_array);
	$option_loop = 0;
	
	while($option_loop < $total_options){
		$facepile[$option_loop] = '';
		$query = "SELECT DISTINCT myo_polling_ip FROM $wpdb->myo_ip WHERE myo_polling_id = $postid AND myo_polling_option = $option_loop";
		$al = $wpdb->get_results($query);
		$votes =  count($al);
		$more = $votes - 2;
		$faces = 0;
							
		foreach ( $al as $face ) 
		{
			$facename = $face->myo_fb_name;
			//get user info
			$user_info = get_userdata($face->myo_polling_ip);
			$userEmail = $user_info->user_email;
			
			$facepile[$option_loop] .=  get_avatar($userEmail, $size = '24' ); 
			
			if($faces >= 1){
				break;
			}
			$faces++;
			
		}

		if($votes > 2){ 
		$facepile[$option_loop] .= "<span class = 'more'>+ $more</span>";
		 } 
		$option_loop++;
	}

	
	$votes = implode(",",$votes_array);
	update_post_meta($poll,'myo-votes',$votes);
	
	//create the facebook publish to feed body content
	
	$url = home_url();
	$fname = $facename;
	$site = get_bloginfo('name');
	$pollt = get_the_title($postid);
	
	$body = $fname . " just answered " .$pollt. " a poll on ". $site;
	$link = get_permalink( $parent );
	
   
	$response['poll'] = $poll;
	$response['option'] = $option_array;
	$response['votes'] = $votes_array;
	$response['total'] = $total_votes;
	$response['chosen'] = $option;
	$response['facepile'] = $facepile;
	$response['body'] = $body;
	$response['link'] = $link;
    $response['rtitle'] = $pollt;
	$response['repo'] = $repo;
	
    echo json_encode($response);
  
  	die(0);
	
}


function myo_bp_poll( $atts ) {
	extract( shortcode_atts( array(
		'poll' => 'true',
		'perc' => 'true',
		'type' => 'true'
	), $atts ) );
    
    global $wp_query,$paged,$post,$wp,$wpdb;
    $wpdb->myo_ip   = $wpdb->prefix . 'myo_ip';

	$ip	= "'".$_SERVER['REMOTE_ADDR']."'";  //for IP logging
	
	$IP = get_option('myo_polling_ip');
	$added = NULL; 
	if($IP == 'yes'){
	$querystr = "SELECT myo_polling_id FROM $wpdb->myo_ip WHERE myo_polling_ip = $ip AND myo_polling_id = $poll";
    $added = $wpdb->get_col($querystr);
	$querystr = "SELECT myo_polling_option FROM $wpdb->myo_ip WHERE myo_polling_ip = $ip AND myo_polling_id = $poll";
    $chosen = $wpdb->get_col($querystr);
	
	}
	
	
	
	
   if($type == 'true'){
   	$type = get_post_meta($post->ID,'myo-type',true);
   }
   if($perc == 'true'){
   	$perc = get_post_meta($post->ID,'myo-display',true);
   }
	
    $content = null;  
    ob_start();

	
	?>
	

<?php	
$app_id =  get_option('myo_polling_app_id');   // can get some buddypress options here
$app_secret =  get_option('myo_polling_app_secret');  // can get some buddypress options here

if($app_id == NULL){   // if NULL use my picsmash app ID as a fallback will complain that domain not a valid domain for app though but FB like buttons would work
	$app_id = '438275232886336';
}

?>

<script type="text/javascript">var parento = '<?php echo $post->ID; ?>';</script>
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : '<?php echo $app_id; ?>', // App ID from the App Dashboard
      status     : true, // check the login status upon init?
      cookie     : true, // set sessions cookies to allow your server to access the session?
      xfbml      : true  // parse XFBML tags on this page?
    });
    
    
   

  };

  // Load the SDK's source Asynchronously
  // Note that the debug version is being actively developed and might 
  // contain some type checks that are overly strict. 
  // Please report such bugs using the bugs tool.
  (function(d, debug){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
     ref.parentNode.insertBefore(js, ref);
   }(document, /*debug*/ false));
</script>


<?php 
//some buddypress tester stuff

$ID =  bp_loggedin_user_id();

$current_user = wp_get_current_user();    //email the current user rather than admin info more likely to reach a human email 
$userEmail = $current_user->user_email;
?>

<?php if($ID != NULL){ ?>
	<script type="text/javascript">
	var myobuddyuser = '<?php echo $ID; ?>';
	var myobuddyname = '<?php echo bp_core_get_user_displayname( $current_user->ID ) ?>';	
	</script>
	<?php
}else{  ?>
	<script type="text/javascript">
	var myobuddyout = 'yes';	
	</script>	
	
<?php }  ?>							

<div class = 'bp_poll'>

        <div class="row">
          <div class="span7">
            			<div class="uiHeader uiHeaderTopBorder mbm pbs uiSideHeader">
				<div class="clearfix uiHeaderTop">
					<div>
						<?php echo "<h6 class='uiHeaderTitle' aria-hidden='true'>". get_the_title($poll) . "</h6></div>";?>
					</div>
				</div>
            
<table class="pollOptions" cellpadding="1" cellspacing="0">
	<tbody>


	<?php
	add_thickbox();
   $poll_options = get_post_meta($poll,'myo-poll-options',true);
   $options = get_post_meta($poll,'myo-options',true);
   $colors = get_post_meta($poll,'myo-colors',true);
   
   $opts = explode(",",$options);

   $cls = explode(",",$colors);
   
   $votes = get_post_meta($poll,'myo-votes',true);
   $votes_array = explode(",",$votes);
   $find = -1; $top = 0; $i = 0; foreach ($votes_array as $n){ if ($n > $top){$find = $i; $top = $n;} $i++;}	
   $total_votes = $wpdb->get_var( "SELECT COUNT(id) FROM $wpdb->myo_ip WHERE myo_polling_id = $poll" );
	echo "<div class = 'rtn-holder'><div id = 'myo-poll-$poll-main' class = 'myo-poll-main'>";
	$myov = $chosen[0];	
	if($myov == null){
		$myov = 999999;
	}
	$top = $find;	

		$i = 0;
		while($i < $poll_options){
			if($total_votes == 0){
				$percent = 0;
			}else{
				$percent = round(100*($votes_array[$i]/$total_votes),0);
			} 
			
	    ?>
			
			
		<tr class="myo-pollbar2">
			<td class="pollResultsBar selectedPollOption"><div class="fbQuestionsPollResultsBar" title="<?php echo $opts[$i];?>"><div class="shaded-<?php echo $i;?> shaded shaded-<?php echo $poll;?>" style="width:<?php echo $percent;?>%"></div>
				<div class="label"><span class="fwb"><?php echo $opts[$i];?></span></div>
				<div class="fbQuestionsPollClickTarget myo-bp-pollbar" data-myo-poll-id = <?php echo $poll; ?> data-myo-poll-opt = <?php echo $i; ?>></div><div class="phs auxlabel"><span class="fwb fcg myo-fb-vote-<?php echo $i;?>-poll-<?php echo $poll;?>"><?php echo $votes_array[$i]; if($votes_array[$i] == 1){ echo ' vote';}else{echo' votes';}?></span></div></div></td>
			
			<td class="pollResultsFacepile">
			<a href = '#TB_inline?height=445&amp;width=400&amp;inlineId=examplePopup<?php echo $i;?>' class = 'thickbox facethick' title = 'people who voted for this option' data-myo-poll-id = <?php echo $poll; ?> data-myo-poll-option = <?php echo $i; ?>>
				<?php
				echo "<div class='uiFacepile uiFacepileSmall' id='myo-poll-$poll-facepile-$i'>";	 
					//get the voters on this option	
						$query = "SELECT * FROM $wpdb->myo_ip WHERE myo_polling_id = $poll AND myo_polling_option = $i";
						$al = $wpdb->get_results($query);
						$votes =  count($al);
						$more = $votes - 2;
						$faces = 0;
						
						foreach ( $al as $face ) 
						{
							$facename = $face->myo_fb_name;
							//get user info
							$user_info = get_userdata($face->myo_polling_ip);
							$userEmail = $user_info->user_email;
							
							echo get_avatar($userEmail, $size = '24' ); 
							
							if($faces >= 1){
								break;
							}
							$faces++;
							
						}


						if($votes > 2){ ?>
						<span class = 'more' title = '<?php echo "+" . $more; ?>'><?php echo "+" . $more; ?></span>
						<?php } ?>
						</a>
						<div id="examplePopup<?php echo $i;?>" style="display:none">
						<table>
						<?php
						$faces = 0;
						foreach ( $al as $face ) 
						{
							
							//get user info
							$user_info = get_userdata($face->myo_polling_ip);
							$userEmail = $user_info->user_email;
							echo "<tr style = 'padding-bottom:2px'>";
							$facename = $user_info->user_login;
							echo "<td>" . get_avatar($userEmail, $size = '50' ) . "</td><td>";
							?>
							<a href="<?php echo bp_core_get_user_domain( $user_info->ID ) ?>"title="<?php echo bp_core_get_user_displayname( $user_info->ID ) ?>">
							<?php
							echo  $facename . "</a></td>";
							echo "<td>";
							?>
							<a href="<?php echo bp_core_get_user_domain( $user_info->ID ) ?>"title="<?php echo bp_core_get_user_displayname($user_info->ID ) ?>">
							<div class = 'uiButton'><span class = 'uiButtonText'>View Profile</span></div></a>
							<?php
							echo "</tr>";
							
							if($faces >= 6){
								break;
							}
							$faces++;
						}
						
						?>
						</table>
						</div>
				</div>
			</td>
			
		</tr>
			

			<?php
			$i++;
			}
		?>


	</tbody>
</table>
         
<!-- fb comments 설정에서 비활성화 할것-->      
<div class = 'padding'></div>
<?php if(get_option('bpfbook') == 'yes'){ ?>
<div class="fb-comments" data-href="<?php echo get_permalink($poll);?>" data-width="550" data-num-posts="2"></div>
<?php } ?>

</div>


<div class = 'span5'>

	<div id="pagelet_question_author" data-referrer="pagelet_question_author">
		<div class="pbm">
			<div class="uiHeader uiHeaderTopBorder mbm pbs uiSideHeader">
				<div class="clearfix uiHeaderTop">
					<div>
						<h6 class="uiHeaderTitle" aria-hidden="true">Asked by</h6></div>
					</div>
				</div>
				<div class="phs">
					<div class="clearfix">
						<div class = 'myo-avat' style = 'padding-right:5px'>
						 <a href="<?php echo bp_core_get_user_domain( get_the_author_meta('ID') ) ?>"title="<?php echo bp_core_get_user_displayname(get_the_author_meta('ID')) ?>">
							<?php echo get_avatar(get_the_author_meta('ID'),32);?>
						</a>
						</div>
						<div class="_29j _29k">
							<div><?php echo get_the_author();?></div>
							<div class="fsm fwn fcg">
								<?php 
								$poll_title = get_the_title($post->ID);
								$newtitle = substr($poll_title, 0, 35) . "...";
								?>
								in <a class="uiLinkSubtle" href="<?php echo get_permalink($post->ID);?>"><?php echo $newtitle;?></a>
								<?php edit_post_link('(Edit)','','',$poll); ?>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		
	<br/><br/>
	
	<div id="pagelet_question_author" data-referrer="pagelet_question_author">
		<div class="pbm">
			<div class="uiHeader uiHeaderTopBorder mbm pbs uiSideHeader">
				<div class="clearfix uiHeaderTop">
					<div>
						<h6 class="uiHeaderTitle" aria-hidden="true">Social Share</h6></div>
					</div>
				</div>
				<div class="phs">
					<?php
					//build the twitter text tweet
					$URL = get_permalink($poll);
					$siteURL = get_site_url();
					$PicsM = "http://pollingplugin.com";
					$text = "Nice question on " . $siteURL. " powered by: ".$PicsM;
					$hash = "#EPIC";
					$QP = "?url=".$URL."&text=".$text."&hashtags=".$hash;
					?>
				
					<a href="https://twitter.com/share<?php echo $QP;?>" class="twitter-share-button" data-lang="en">Tweet</a>
					<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
					
					
			
					<div class="g-plusone" data-size="medium" data-annotation="inline" data-width="225" data-href="<?php echo $URL; ?>"></div>
					<br/>
			
					<script type="text/javascript">
					  (function() {
					    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
					    po.src = 'https://apis.google.com/js/plusone.js';
					    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
					  })();
					</script>
		
					<div class="fb-like" data-href="<?php echo $URL; ?>" data-layout="button_count" data-send="true" data-width="220" data-show-faces="false" data-font="arial"></div>
					<br/><br/>

					<div class="clearfix"></div>
				</div>
			</div>
		</div>
		
		
		<div id="pagelet_question_author" data-referrer="pagelet_question_author">
		<div class="pbm">
			<div class="uiHeader uiHeaderTopBorder mbm pbs uiSideHeader">
				<div class="clearfix uiHeaderTop">
					<div>
						<h6 class="uiHeaderTitle" aria-hidden="true">Poll Statistics</h6></div>
					</div>
				</div>
				<div class="phs">
					<?php

					if(get_option('bpjustone') == 'yes'){
						if($total_votes == 1){
								$vote = 'person has';
							}else{
								$vote = 'people have';
							}
						echo number_format((double)$total_votes,0) . " " . $vote . " voted on this poll.";
						}else{
							if($total_votes == 1){
								$vote = 'vote';
							}else{
								$vote = 'votes';
							}
						echo number_format((double)$total_votes,0) . " " . $vote . " on this poll.";
						}
					?>
				
	

					<div class="clearfix"></div>
				</div>
			</div>
		</div>
	
		<!--div class = 'powered'>
						<div class="mvs fsm"><span><?php echo '<img src="' .plugins_url( 'i/pollyicon.png' , __FILE__ ). '" />';?><a href="http://codecanyon.net/item/wordpress-easy-polling-plugin/3493930?ref=mikemayhem3030" target="_blank">Easy Polling Plugin</a>.</span></div>
					</div -->  
					
		
	</div>


	


	</div> 
	

	

	
	
	</div>
 <!-- SIDEBAR SHOULD BE TO THE SIDE -->

<?php	
	
    $content = ob_get_contents();
    ob_end_clean();
    return $content;
}

add_shortcode("myo_bp_poll", "myo_bp_poll");

#} Send registration info to my server
function bpolls_sendReg($e='',$na='',$pl=''){

   global $bp_urls;	
			if( function_exists('curl_init') ) { 
					$postData = array('ori'=>get_site_url());
					$postData['e'] = $e; //email
					$postData['na'] = $na;  //name
					$postData['pl'] = $pl;  //plugin

					
					$fields = ''; foreach($postData as $key => $value) $fields .= $key . '=' . $value . '&'; rtrim($fields, '&');
					$ch = curl_init($bp_urls['regCheck']);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_setopt($ch, CURLOPT_POST, count($postData));
					curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
					curl_setopt($ch, CURLOPT_TIMEOUT, 10);
					$regDets = curl_exec($ch);
					
					curl_close($ch);
					return $regDets;
			} # else, cry?			
			return  $false;
}



//code for the warnings and auto updating
$api_url = $bp_urls['updateCheck'];
$plugin_slug = basename(dirname(__FILE__));


// Take over the update check
add_filter('pre_set_site_transient_update_plugins', 'bpolls_check_for_plugin_update');

function bpolls_check_for_plugin_update($checked_data) {
	global $api_url, $plugin_slug;

	//Comment out these two lines during testing.
	if (empty($checked_data->checked))
		return $checked_data;

	$args = array(
		'slug' => $plugin_slug,
		'version' => $checked_data->checked[$plugin_slug .'/'. $plugin_slug .'.php'],
	);
	$request_string = array(
			'body' => array(
				'action' => 'basic_check', 
				'request' => serialize($args),
				'api-key' => md5(get_bloginfo('url'))
			),
			'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url')
		);

	// Start checking for an update
	$raw_response = wp_remote_post($api_url, $request_string);

	if (!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
		$response = unserialize($raw_response['body']);

	if (is_object($response) && !empty($response)) // Feed the update data into WP updater
		$checked_data->response[$plugin_slug .'/'. $plugin_slug .'.php'] = $response;

	return $checked_data;
}



add_filter('plugins_api', 'bpolls_plugin_api_call', 10, 3);

function  bpolls_plugin_api_call($def, $action, $args) {
	global $plugin_slug, $api_url;

	if ($args->slug != $plugin_slug)
		return false;

	// Get the current version
	$plugin_info = get_site_transient('update_plugins');
	$current_version = $plugin_info->checked[$plugin_slug .'/'. $plugin_slug .'.php'];
	$args->version = $current_version;

	$request_string = array(
			'body' => array(
				'action' => $action, 
				'request' => serialize($args),
				'api-key' => md5(get_bloginfo('url'))
			),
			'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url')
		);

	$request = wp_remote_post($api_url, $request_string);

	if (is_wp_error($request)) {
		$res = new WP_Error('plugins_api_failed', __('An Unexpected HTTP Error occurred during the API request.</p> <p><a href="?" onclick="document.location.reload(); return false;">Try again</a>','PicsMash'), $request->get_error_message());
	} else {
		$res = unserialize($request['body']);

		if ($res === false)
			$res = new WP_Error('plugins_api_failed', __('An unknown error occurred','PicsMash'), $request['body']);
	}

	return $res;
}


